package com.demo.ohos_zblibrary.wxdemo;

import com.demo.ohos_zblibrary.ResourceTable;
import com.demo.ohos_zblibrary.imageloader.UILImageLoader;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridAbility;
import com.lzy.imagepicker.ui.ImagePreviewAbility;
import com.lzy.imagepicker.view.CropImageView;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ListDialog;
import zuo.biao.library.util.Log;

import java.util.ArrayList;
import java.util.List;
/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * 修订历史：微信图片选择的Adapter
 */
public class WxDemoAbility extends Ability implements ImagePickerAdapter.OnRecyclerViewItemClickListener {
    /**
     * 图片image
     */
    public static final int IMAGE_ITEM_ADD = -1;
    /**
     * 请求CODE_SELECT
     */
    public static final int REQUEST_CODE_SELECT = 100;
    /**
     *请求CODE_PREVIEW
     */
    public static final int REQUEST_CODE_PREVIEW = 101;

    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList; // 当前选择的所有图片
    private int maxImgCount = 8; // 允许选择图片最大数

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_activity_wxdemo);

        // 最好放到 Application oncreate执行
        initImagePicker();
        initWidget();
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new UILImageLoader()); // 设置图片加载器
        imagePicker.setShowCamera(true); // 显示拍照按钮
        imagePicker.setCrop(true); // 允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); // 是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount); // 选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE); // 裁剪框的形状
        imagePicker.setFocusWidth(800); // 裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800); // 裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000); // 保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000); // 保存文件的高度。单位像素
    }

    private void initWidget() {
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_recyclerView);
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(WxDemoAbility.this);
        listContainer.setItemProvider(adapter);
    }

    private ListDialog showDialog(IDialog.ClickedListener listener, List<String> names) {
        ListDialog dialog = new ListDialog(this, ListDialog.SINGLE);
        String[] namesArray = names.toArray(new String[names.size()]);
        dialog.setItems(namesArray);
        dialog.setOnSingleSelectListener(listener);
        if (!this.isTerminating()) {
            dialog.show();
        }
        return dialog;
    }

    @Override
    public void onItemClick(Component view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog(new IDialog.ClickedListener() {
                            @Override
                            public void onClick(IDialog iDialog, int pos) {
                                Operation operation =
                                        new Intent.OperationBuilder()
                                                .withDeviceId("")
                                                .withBundleName("com.lzy.imagepickerdemo")
                                                .withAbilityName("com.lzy.imagepicker.ui.ImageGridAbility")
                                                .build();
                                switch (pos) {
                                    case 0: // 直接调起相机
                                        ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                                        Intent intent = new Intent();
                                        intent.setOperation(operation);
                                        intent.setParam(ImageGridAbility.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                        startAbilityForResult(intent, REQUEST_CODE_SELECT);
                                        iDialog.hide();
                                        break;
                                    case 1:
                                        // 打开选择,本次允许选择的数量
                                        ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                                        Intent intent1 = new Intent();
                                        intent1.setOperation(operation);
                                        startAbilityForResult(intent1, REQUEST_CODE_SELECT);
                                        iDialog.hide();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        },
                        names);
                break;
            default:
                toImagePreviewAbility(position);
                break;
        }
    }

    private void toImagePreviewAbility(int position) {
        Operation operation =
                new Intent.OperationBuilder()
                        .withDeviceId("")
                        .withBundleName(ImagePreviewAbility.class.getPackage().getName())
                        .withAbilityName(ImagePreviewAbility.class.getName())
                        .build();
        // 打开预览
        Intent intentPreview = new Intent();
        intentPreview.setOperation(operation);
        intentPreview.setParam(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
        intentPreview.setParam(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
        intentPreview.setParam(ImagePicker.EXTRA_FROM_ITEMS, true);
        startAbilityForResult(intentPreview, REQUEST_CODE_PREVIEW);
    }

    ArrayList<ImageItem> images = null;

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent data) {
        super.onAbilityResult(requestCode, resultCode, data);
        try {
            if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
                // 添加图片返回
                if (data != null && requestCode == REQUEST_CODE_SELECT) {
                    images = (ArrayList<ImageItem>) data.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS);
                    if (images != null) {
                        selImageList.addAll(images);
                        adapter.setImages(selImageList);
                    }
                }
            } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
                // 预览图片返回
                if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                    images = (ArrayList<ImageItem>) data.getSerializableParam(ImagePicker.EXTRA_IMAGE_ITEMS);
                    if (images != null) {
                        selImageList.clear();
                        selImageList.addAll(images);
                        adapter.setImages(selImageList);
                    }
                }
            }
        } catch (Exception e) {
            Log.error("Exception",e.toString());
        }

    }
}
